<!-- 设备管理-设备运行-设备运行记录新增页面 -->
<template>
  <div v-if="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin: 16px 0 -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
        <EditDropDown dropdownTitle="设备信息">
          <template v-slot:content>
            <px-row>
              <px-col :span="12">
                <EquipClassSelect :isRequired="true" :className="formValue.className" :isDisabled="props.planId" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="12">
                <EquipSystemTree
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCode="formValue.systemCode"
                  :currentType="props.drawerType"
                  :isDisabled="props.planId"
                  @changeAllSystemCodes="changeAllSystemCodes"
                  @changeSystemCodes="changeSystemCodes"
                  @clearSystem="clearSystem"
                  @getEditSystemCodes="getEditSystemCodes"
                />
              </px-col>
              <px-col :span="12">
                <EquipCategorySelect
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCodes="systemCodes"
                  :categoryId="formValue.categoryId"
                  :isDisabled="props.planId"
                  @changeCategory="changeCategory"
                />
              </px-col>
              <px-col :span="12">
                <EquipTypeSelect
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCodes="systemCodes"
                  :categoryId="formValue.categoryId"
                  :typeId="formValue.typeId"
                  :isDisabled="props.planId"
                  @changeType="changeType"
                />
              </px-col>
              <px-col :span="12">
                <EquipModelSelect
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCodes="systemCodes"
                  :categoryId="formValue.categoryId"
                  :typeId="formValue.typeId"
                  :modelId="formValue.modelId"
                  :isDisabled="props.planId"
                  @changeModel="changeModel"
                />
              </px-col>
              <px-col :span="12">
                <px-form-item label="设备编号" prop="eqpId">
                  <px-input
                    v-model="formValue.eqpId"
                    placeholder="请点击选择"
                    maxlength="50"
                    disabled
                    style="width: calc(100% - 108px); margin-right: 8px"
                  />
                  <px-button type="primary" plain style="width: 100px" @click="dialogVisible = true" :disabled="props.planId">选择设备</px-button>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="设备名称" prop="eqpName">
                  <px-input v-model="formValue.eqpName" placeholder="选择设备编号后自动带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
        <EditDropDown dropdownTitle="设备运行状态">
          <template v-slot:content>
            <px-row>
              <px-col :span="12">
                <px-form-item label="设备运行状态" prop="eqpRunStatus">
                  <px-select
                    v-model="formValue.eqpRunStatus"
                    placeholder="请选择设备运行状态"
                    filterable
                    clearable
                    style="width: 100%"
                    :disabled="props.planId"
                  >
                    <px-option v-for="item in eqpRunStatusList" :key="item.id" :label="item.name" :value="item.value" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="状态原因" prop="downCauseCode">
                  <px-select
                    v-model="formValue.downCauseCode"
                    placeholder="请选择状态原因"
                    filterable
                    clearable
                    :disabled="props.planId"
                    style="width: 100%"
                    @change="handleStatusChange"
                  >
                    <px-option v-for="item in downCauseCodeList" :key="item.id" :label="item.name" :value="item.code" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="状态类型" prop="downTypeName">
                  <px-input v-model="formValue.downTypeName" placeholder="选择状态原因后自动带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="状态开始时间" prop="startTime">
                  <px-date-picker
                    v-model="formValue.startTime"
                    style="width: 100%"
                    placeholder="请选择状态开始时间"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :clearable="false"
                    @change="changeStartTime"
                    :disabled="props.planId"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="状态结束时间" prop="endTime">
                  <px-date-picker
                    v-model="formValue.endTime"
                    style="width: 100%"
                    placeholder="请选择状态结束时间"
                    type="datetime"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    clearable
                    @change="changeEndTime"
                    :disabled="props.planId"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="状态时长" prop="runTimes">
                  <px-input v-model="formValue.runTimes" placeholder="根据开始时间和结束时间计算" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="详细原因" prop="remark">
                  <px-input
                    v-model="formValue.remark"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    placeholder="请输入详细原因"
                    maxlength="1000"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </template>
        </EditDropDown>
      </px-form>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button v-if="props.drawerType === 'add'" @click="getNewRunRecord">载入上次填写内容</px-button>
      <px-button type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </div>
  <!-- 选择设备弹窗 -->
  <EquipIdSelectDialog
    :visible="dialogVisible"
    :className="formValue.className"
    :systemCodes="systemCodes"
    :categoryId="formValue.categoryId"
    :typeId="formValue.typeId"
    :modelId="formValue.modelId"
    @closeEquipDialog="closeEquipDialog"
    @changeEqpId="changeEqpId"
  />
</template>

<script setup lang="ts">
import { queryDictData } from "@/api/common";
import { addRunRecord, getRunStatusReasonSelect, getRunRecordNew, getRunOperatePlan } from "@/api/equip/runManage";
import { formatDuration } from "@/utils/pengxi";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipCategorySelect from "@/views/all/equip/components/EquipCategorySelect.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipIdSelectDialog from "@/views/all/equip/components/EquipIdSelectDialog.vue";
import EquipModelSelect from "@/views/all/equip/components/EquipModelSelect.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import EquipTypeSelect from "@/views/all/equip/components/EquipTypeSelect.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import { cloneDeep, isEqual } from "@pureadmin/utils";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps(["isMain", "isView", "drawerType", "rowData", "planId"]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);

// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  formValue: {
    className: "",
    systemCode: "",
    categoryId: null,
    typeId: null,
    modelId: null,
    eqpId: "",
    eqpName: ""
  },
  eqpRunStatusList: [], // 运行状态列表
  downCauseCodeList: [], // 状态原因列表
  isDisabled: false, // 禁用-自动上报不允许编辑设备信息，手动上报可以编辑设备信息
  systemCodes: [],
  dialogVisible: false,
  differContent: null
});
const { formValue, eqpRunStatusList, downCauseCodeList, isDisabled, systemCodes, dialogVisible, differContent } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  eqpId: [{ required: true, message: "设备编号不能为空", trigger: "blur" }],
  eqpRunStatus: [{ required: true, message: "设备运行状态不能为空", trigger: "blur" }],
  startTime: [{ required: true, message: "状态开始时间不能为空", trigger: "change" }],
  downCauseCode: [{ required: true, message: "状态原因不能为空", trigger: "blur" }]
}));

// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    isDisabled.value = false;
    formRef.value?.resetFields();
    systemCodes.value = [];
    eqpRunStatusList.value = await queryDictData({ typeCode: "EQP_RUN_STATUS" });
    downCauseCodeList.value = await getRunStatusReasonSelect({});
    if (props.drawerType === "add" && !props.planId) {
      formValue.value = {
        className: "",
        systemCode: "",
        categoryId: null,
        typeId: null,
        modelId: null,
        eqpId: "",
        eqpName: ""
      };
    } else if (props.drawerType === "add" && props.planId) {
      const planId = props.planId;
      const data = await getRunOperatePlan(planId);
      formValue.value = data;
      formValue.value.startTime = data?.factStartTime;
    } else if (props.drawerType === "edit") {
      const rowData = JSON.parse(JSON.stringify(props.rowData));
      formValue.value = rowData;
      const { reportType } = rowData;
      if (reportType === "AUTOMATIC_REPORT") {
        isDisabled.value = true;
      } else if (reportType === "MANUAL_REPORT") {
        isDisabled.value = false;
      }
    }
    differContent.value = cloneDeep(formValue.value);
  }
});

// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (formValue.value.endTime <= formValue.value.startTime) {
        PxMessage.warning("实际开始时间不能晚于或等于实际结束时间！");
        return;
      }
      if (props.drawerType === "add") {
        const params = {
          eqpId: formValue.value.eqpId,
          eqpRunStatus: formValue.value.eqpRunStatus,
          startTime: formValue.value.startTime,
          endTime: formValue.value.endTime,
          downCauseCode: formValue.value.downCauseCode,
          remark: formValue.value.remark
        };
        if (props.planId) {
          params.planId = props.planId;
        }
        await addRunRecord(params);
        PxMessage.success("新增成功");
        emits("backMainPage");
        emits("queryTable");
      } else if (props.drawerType === "edit") {
        const params = {
          id: props.rowData.id,
          eqpId: formValue.value.eqpId,
          eqpRunStatus: formValue.value.eqpRunStatus,
          startTime: formValue.value.startTime,
          endTime: formValue.value.endTime,
          downCauseCode: formValue.value.downCauseCode,
          remark: formValue.value.remark
        };
        await addRunRecord(params);
        PxMessage.success("编辑成功");
        emits("backMainPage");
        emits("queryTable");
      }
      formValue.value = {
        className: "",
        systemCode: "",
        categoryId: null,
        typeId: null,
        modelId: null,
        eqpId: "",
        eqpName: ""
      };
    }
  });
};
// 返回主页面
const backMainPage = () => {
  const differCont = cloneDeep(formValue.value);
  if (isEqual(differContent.value, differCont)) {
    formRef.value?.resetFields();
    differContent.value = null;
    emits("backMainPage");
    return;
  }
  PxMessageBox.confirm("确认退出页面？退出后内容不会保存", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      formRef.value?.resetFields();
      differContent.value = null;
      emits("backMainPage");
    })
    .catch(() => {});
};
// 获取最新一条运行记录
const getNewRunRecord = async () => {
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));
  const data = await getRunRecordNew(userInfo.userId);
  if (!data) {
    PxMessage.warning("您尚未有历史提交记录，无可载入内容");
    return;
  }
  const rowData = JSON.parse(JSON.stringify(data));
  formValue.value = rowData;
  const { reportType } = rowData;
  if (reportType === "MANUAL_REPORT") {
    isDisabled.value = false;
  }
};
// 关闭子级设备dialog弹窗
const closeEquipDialog = () => {
  dialogVisible.value = false;
};
// 开始时间
const changeStartTime = () => {
  if (formValue.value.startTime && formValue.value.endTime) {
    if (formValue.value.startTime > formValue.value.endTime) {
      formValue.value.endTime = formValue.value.startTime;
    }
    // 计算运行时长
    const timeRange =
      Date.parse(new Date(formValue.value.endTime.replace(/-/g, "/"))) - Date.parse(new Date(formValue.value.startTime.replace(/-/g, "/")));
    formValue.value.runTimes = timeRange === 0 ? 0 : timeRange ? formatDuration(timeRange) : "-";
  } else {
    formValue.value.runTimes = "-";
  }
};
// 结束时间
const changeEndTime = () => {
  if (formValue.value.startTime && formValue.value.endTime) {
    if (formValue.value.startTime > formValue.value.endTime) {
      formValue.value.startTime = formValue.value.endTime;
    }
    // 计算运行时长
    const timeRange =
      Date.parse(new Date(formValue.value.endTime.replace(/-/g, "/"))) - Date.parse(new Date(formValue.value.startTime.replace(/-/g, "/")));
    formValue.value.runTimes = timeRange === 0 ? 0 : timeRange ? formatDuration(timeRange) : "-";
  } else {
    formValue.value.runTimes = "-";
  }
};
// 状态原因改变，获取状态类型
const handleStatusChange = val => {
  const arr = downCauseCodeList.value.filter(item => {
    return item.code === val;
  });
  if (arr && arr.length > 0) {
    formValue.value.downTypeName = arr[0].downTypeName;
  }
};

// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  systemCodes.value = [];
  if (!isOnlyClass) {
    formRef.value?.resetFields(["systemCode", "categoryId", "typeId", "modelId", "eqpId", "eqpName"]);
  }
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  formValue.value.className = val2;
  formValue.value.systemCode = val3;
  systemCodes.value = val4;
  formRef.value?.resetFields(["categoryId", "typeId", "modelId", "eqpId", "eqpName"]);
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  formValue.value.systemCode = val;
  systemCodes.value = val2;
  formRef.value?.resetFields(["categoryId", "typeId", "modelId", "eqpId", "eqpName"]);
};

// 用于编辑时的页面回显，保证类型型号过滤是正确的
const getEditSystemCodes = (val, val2) => {
  formValue.value.systemCode = val;
  systemCodes.value = val2;
};
// 系统组件值改变触发
const clearSystem = val => {
  systemCodes.value = [];
  formRef.value?.resetFields(["systemCode", "categoryId", "typeId", "modelId", "eqpId", "eqpName"]);
};
// 改变设备总称，清空设备类型和设备型号
const changeCategory = val => {
  formValue.value.categoryId = val;
  formRef.value?.resetFields(["typeId", "modelId", "eqpId", "eqpName"]);
};
// 改变设备类型，清空设备型号
const changeType = (val, val2) => {
  formValue.value.categoryId = val2;
  formValue.value.typeId = val;
  formRef.value?.resetFields(["modelId", "eqpId", "eqpName"]);
};
// 改变设备型号
const changeModel = (val, val2, val3) => {
  formValue.value.categoryId = val2;
  formValue.value.typeId = val3;
  formValue.value.modelId = val;
  formRef.value?.resetFields(["eqpId", "eqpName"]);
};
// 改变设备编号
const changeEqpId = equipDetail => {
  formValue.value.className = equipDetail?.className || "";
  formValue.value.systemCode = equipDetail?.systemCode || "";
  systemCodes.value = [];
  formValue.value.categoryId = equipDetail?.categoryId || "";
  formValue.value.typeId = equipDetail?.typeId || "";
  formValue.value.modelId = equipDetail?.modelId || "";
  formValue.value.eqpId = equipDetail?.eqpId || "";
  formValue.value.eqpName = equipDetail?.eqpName || "";
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
